package com.ericsson.web.core;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.hsqldb.Server;

public class HSQLDBListener implements ServletContextListener {

	private String dbName = null;
	private int dbPort = -1;
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		Connection conn = null;
		try {
			Class.forName("org.hsqldb.jdbcDriver");
			conn = DriverManager.getConnection(
					"jdbc:hsqldb:hsql://localhost:" + dbPort + "/" + dbName, "sa", "");
			Statement stmt = conn.createStatement();
			stmt.executeUpdate("SHUTDOWN;");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		dbName = sce.getServletContext().getInitParameter("hsql.dbName");
		if (dbName == null || dbName.isEmpty()) {
			System.out.println("Cant' get hsqldb.dbName from web.xml Context Param");
			return;
		}
		Constants.setDbName(dbName);
		
		try {
			dbPort = Integer.parseInt(sce.getServletContext().getInitParameter(
					"hsql.port"));
		} catch (Exception e) {
			dbPort = 9999;
		}
		Constants.setDbPort(dbPort);
		
		String path = sce.getServletContext().getInitParameter("hsql.dbPath");
		File dbDir = new File(path);
		if (!dbDir.exists()) {
			if (!dbDir.mkdirs()) {
				System.out.println("Can not create DB Dir for Hsql:" + dbDir);
				return;
			}
		}
		if (!path.endsWith("/")) {
			path = path + "/";
		}
		
		startServer(path);
	}

	private void startServer(String dbPath) {
		Server server = new Server();
		server.setDatabaseName(0, dbName);
		server.setDatabasePath(0, dbPath + dbName);
		if (dbPort != -1) {
			server.setPort(dbPort);
		}
		server.setSilent(true);
		server.start();
		System.out.println("HSQLDB started...");
	}
}
